import time
import logging
from fastapi import Request, Response
from fastapi.responses import JSONResponse
import json
from typing import Callable

logger = logging.getLogger(__name__)


def setup_request_logging(app):
    """设置请求日志中间件"""

    @app.middleware("http")
    async def log_requests(request: Request, call_next: Callable) -> Response:
        """记录HTTP请求和响应"""
        start_time = time.time()

        # 记录请求信息
        request_id = str(int(time.time() * 1000000))  # 简单的唯一ID
        client_ip = request.client.host if request.client else "unknown"
        method = request.method
        url = str(request.url)

        # 记录请求体（如果不是大文件）
        body_info = ""
        if "multipart/form-data" not in request.headers.get("content-type", ""):
            try:
                body = await request.body()
                if body and len(body) < 1024:  # 只记录小于1KB的请求体
                    body_info = f" body={body.decode()}"
            except Exception:
                pass

        logger.info(
            f"[{request_id}] {client_ip} {method} {url}{body_info}"
        )

        # 处理请求
        response = await call_next(request)

        # 计算处理时间
        process_time = time.time() - start_time

        # 记录响应信息
        logger.info(
            f"[{request_id}] {method} {url} - "
            f"Status: {response.status_code} - "
            f"Time: {process_time:.3f}s"
        )

        # 添加处理时间到响应头
        response.headers["X-Process-Time"] = str(process_time)
        response.headers["X-Request-ID"] = request_id

        return response